### adsb_parser/replay.py

import os
import pyshark
import socket
import time
import asyncio
from parser import resource_path

def start_pcap_replay(pcap_file, target_ip='127.0.0.1', target_port=62325, delay=0.1, stop_flag=None, logger=None):
    """
    从PCAP文件中回放UDP 62325数据到指定IP端口。
    支持在非主线程中运行，支持中途停止。
    logger: 可选日志记录函数（如 GUI 状态栏）
    """
    def log(msg, color="white"):
        if logger:
            logger(msg, color)
        else:
            print(msg)

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        # tshark_path = r"D:\\Program Files\\Wireshark\\tshark.exe"
        tshark_path = resource_path(os.path.join("wireportable", "tshark.exe"))
        capture = pyshark.FileCapture(
            pcap_file,
            display_filter="udp.port == 62325",
            tshark_path=tshark_path
        )
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        for pkt in capture:
            if stop_flag and stop_flag.is_set():
                log("[回放] 用户请求中止", "red")
                break
            try:
                payload = bytes.fromhex(pkt.udp.payload.replace(':', ''))
                sock.sendto(payload, (target_ip, target_port))
                time.sleep(delay)
            except Exception as e:
                log(f"[回放] 跳过错误帧：{e}", "orange")

        sock.close()
        log("[回放] 回放完成", "green")
    except Exception as ex:
        log(f"[回放] 加载或回放失败: {ex}", "red")
